## Git Modules

# get git path
Function Get-WorktreeDir {
    $result = git worktree list --porcelain
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Not found git worktree dir"
        return ""
    }
    $wt = ( -Split $result[0])[1]
    return "$wt"
}


Function IsNotNormalFile($file) {
    $gitfiles = @(
        ".gitignore",
        ".gitattributes",
        ".gitmodules"
    )
    foreach ($_ in $gitfiles) {
        if ($_ -eq $file) {
            return $True
        }
    }
    return $False
}

Function Get-CurrentGitDir {
    param(
        [string]$Worktree
    )
    if ([System.String]::IsNullOrEmpty($Worktree)) {
        $dir = Get-WorktreeDir
    }
    else {
        $dir = $Worktree
    }
    $xdir = "$dir/.git"
    if (!(Test-Path $xdir)) {
        return $dir
    }
    # Need use -Force , .git is Hide Directory
    $file = Get-Item -Force -Path $xdir
    if ($file -is [System.IO.DirectoryInfo]) {
        return $xdir
    }
    $zdir = ( -Split (Get-Content -Path $xdir)[0])[1]
    $realdir = Resolve-Path "$file/$zdir"
    return $realdir
}

Function Get-Changeset {
    param(
        [string]$Commit
    )
    if ([System.String]::IsNullOrEmpty($Commit)) {
        $arg = "--cached"
    }
    else {
        $arg = "$Commit"
        
    }
    $files = New-Object -TypeName System.Collections.ArrayList
    git diff $arg --name-status|ForEach-Object {
        $file = -Split $_
        $obj = @{
            "status" = $file[0];
            "path"   = $file[1]
        }
        $files.Add($obj)|Out-Null
    }
    return $files
}
